package Group9.TodoManager.Actions;

import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.ImageIcon;

import Group9.TodoManager.Settings;
import Group9.TodoManager.Data.Task;
import Group9.TodoManager.Data.Interface.ITableModel;
import Group9.TodoManager.DataStore.Repository;

/**
 * CompleteAction class is used for managing "mark task complete" operation
 * When a task is selected and marked as complete, task's status is updated
 * to complete. This change is also applied to the xml file. Therefore when
 * application is restarted, a completed task is still completed.
 * @author volkan cambazoglu
 *
 * @param <T>
 */
public class CompleteAction<T> extends TodoManagerAction {
	private Repository<T> repository;
	private ITableModel<T> tableModel;

	/**
	 * This creates an action to mark a task complete
	 * @param name name of the action
	 * @param icon icon of the action
	 * @param table tableModel of the application
	 * @param repo repository of the application
	 */
	public CompleteAction(String name, ImageIcon icon, ITableModel<T> table, 
													Repository<T> repo) {
		super(name, icon);
		putValue(Action.SHORT_DESCRIPTION, name);
        tableModel = table;
        repository = repo;
	}

	/**
	 * When this action is performed, it will mark the selected task as complete.
	 * This change is also applied to the repository, which is the XML file in this
	 * case.
	 * @param e event
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		Task task = (Task) tableModel.getRowObject(tableModel.getSelectedRowIndex());
		repository.removeItem((T) task);
        repository.Commit();
        tableModel.removeRowAt(tableModel.getSelectedRowIndex());
		task.setStatus(Task.COMPLETE);
		task.setProgress(100);
		repository.addNewItem((T) task);
        repository.Commit();
        tableModel.addRow((T) task);
    	Settings.displayMessage(
    		Settings.getCurrentResourceBundle().getString("Message.TaskComplete"));
	}
}
